package com.xck.clouddisk.controller;

import com.alibaba.fastjson.JSON;
import com.xck.clouddisk.response.Result;
import com.xck.clouddisk.service.AliMsgService;
import com.xck.clouddisk.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api
@RestController
@RequestMapping("/alismsservice/ali-msg")
@CrossOrigin
public class AliMsgController {

    @Resource
    private AliMsgService aliMsgService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * data {}  params:string
     */
    @PostMapping("/sendMsg")
    public Result sendMsg(String phoneNumber){
        //1.直接从redis中获取验证码
        //如果不为空,说明redis中已经存在验证码了
        Object code = redisTemplate.opsForValue().get(phoneNumber);
        if(!StringUtils.isEmpty(code)){
            return Result.ok().data("code",code);
        }else{
            String sixBitRandom = RandomUtil.getSixBitRandom();
            //如果不存在,在获取验证码之后还需要存放到redis中
            redisTemplate.opsForValue().set(phoneNumber,sixBitRandom,5, TimeUnit.MINUTES);
            Map<String,Object> map = new HashMap<>(2);
            map.put("code",sixBitRandom);
            String templateParam = JSON.toJSON(map).toString();
            aliMsgService.sendSms(phoneNumber, templateParam);
            return Result.ok().data(map);
        }
    }
}
